package org.mybatis.demo.plugins;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

/**
 * @author yangjian
 */
@Intercepts({@Signature(
  type = Executor.class, // 拦截对象类型，只能是 Executor,ParameterHandler,ResultSetHandler,StatementHandler 中的一个
  method = "query", // 拦截的方法名称，并不是所有的方法都允许拦截
  args = { // 拦截方法的参数，考虑到方法重载，不同的参数对应不同的方法签名
    MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class
  })})
public class TestPlugin implements Interceptor {
  @Override
  public Object intercept(Invocation invocation) throws Throwable
  {
    System.out.println("===== 测试拦截器 ======");
    Object[] args = invocation.getArgs();
    MappedStatement mappedStatement = (MappedStatement) args[0];
    // 打印 SQL 语句
    System.out.println(mappedStatement.getBoundSql(args[1]).getSql());
    // 调用原始对象方法
    return invocation.proceed();
  }

  @Override
  public Object plugin(Object target)
  {
    return Interceptor.super.plugin(target);
  }

  @Override
  public void setProperties(Properties properties)
  {
    Interceptor.super.setProperties(properties);
  }
}
